package com.cn.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.cn.domain.Product;
import com.cn.service.ProductService;
import com.cn.service.impl.ProductServiceImpl;
import com.cn.utils.UploadUtils;

public class AddProductServlet extends BaseServlet {

	//ProductService ps = new ProductServiceImpl();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			
			ServletFileUpload upload = new ServletFileUpload(factory);

			if(!upload.isMultipartContent(request)){
				throw new RuntimeException("当前不是多段式提交!");
			}
			upload.setHeaderEncoding("UTF-8");
			List<FileItem> list = null;
			try {
				 list = upload.parseRequest(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
				throw new RuntimeException("解析失败！");
			}
			Map<String,String[]> params = new HashMap<String,String[]>();
			for (FileItem fi : list) {
				if (fi.isFormField()) {
					String key = fi.getFieldName();
					String value = fi.getString("UTF-8");
					params.put(key, new String[]{value});
				} else {
					System.out.println("文件提交的键：" + fi.getFieldName());
					System.out.println("文件原始名称：" + fi.getName());
					System.out.println("文件的mime类型：" + fi.getContentType());
					System.out.println("文件长度：" + fi.getSize());
					
					String uuid = UUID.randomUUID().toString();
					String dirpath = getServletContext().getRealPath("/uploadFile");
					String datepath =  UploadUtils.getDatePath(new Date());
					File test = new File(dirpath+datepath);
					if(!test.exists()){
						test.mkdirs();
					}
					
					InputStream is = fi.getInputStream();
					FileOutputStream fos = new FileOutputStream(dirpath+datepath+uuid);
					params.put("url",new String[]{"/uploadFile"+datepath+uuid});
					System.out.println("/uploadFile"+datepath+uuid);
					IOUtils.copy(is, fos);
					is.close();
					fos.close();
					fi.delete();
				}
			}
			Product p = new Product();
			try {
				BeanUtils.populate(p, params);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ps.addProduct(p);
			response.sendRedirect("/day1302/admin/products/list.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/admin/products/add.jsp").forward(request, response);
		}
//		try {
//			Product p = new Product();
//			try {
//				BeanUtils.populate(p, request.getParameterMap());
//			} catch (IllegalAccessException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (InvocationTargetException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			ps.addProduct(p);
//			response.sendRedirect("/day1302/admin/products/list.jsp");
//		} catch (Exception e) {
//			e.printStackTrace();
//			request.setAttribute("error", e.getMessage());
//			request.getRequestDispatcher("/products/add.jsp").forward(request, response);
//		}
	}

}
